# -*- coding: utf-8 -*-
import logging
import random
import time
from traceback import format_exc
from scrapy.utils.project import get_project_settings
from zc_core.dao.cookie_dao import CookieDao
from zc_core.middlewares.proxies.cached_pool import CachedProxyPool
from zc_core.util.instance_builder import build_instance

logger = logging.getLogger('login')

import requests


class SeleniumLogin(object):
    # 登录地址
    login_url = 'https://mla.iccec.cn/apis/mla/users/signup/login'

    index_url = 'https://ego.ctg.com.cn/mall-cli-portal/static/pages/index/index.html#/index/index'
    cookie_white_list = ['access_token', 'refresh_token', 'acw_tc']

    def __init__(self, timeout=60):
        settings = get_project_settings()
        self.max_login_retry = settings.get('MAX_LOGIN_RETRY', 1)
        # 构建校验器对象
        proxy_pool_class = settings.get('PROXY_POOL_CLASS', '')
        if proxy_pool_class:
            self.pool = build_instance(proxy_pool_class, settings)
        else:
            self.pool = CachedProxyPool(settings)
        self.accounts = settings.get('ACCOUNTS', [])
        self.person = requests.Session()

    def login(self):
        proxy = self.pool.get_proxy()

        logger.info('login account: %s' % "13328059510")
        proxies = {
            # "http": "http://{}".format(proxy),
            "https": "https://{}".format(proxy)
        }
        data = {"username": "13328059510",
                "password": "V1o5W6GVbAOwe7hXFTrOuk5B8hwt1FdgGE20kFuMIZkceGoRLLirSK3KMPGtsfQvEmEZZZLfeLfbvUjn5DovtV31ekKIFPlZOc/qU16wQVWUE0NqAiZVODVmhMCBaIcMaGPmNvbxdSuU1ZtwPwtDYkVrsE2W27nRTMR+xVs6HATJLLxSrPmu+JGO1bfuDoAG55TGQ9niq/00NQKFkG/4QwolRhtkgHKbdLISivaRG9Z2Ajyjgn31vzu8ofZR9jOKczj9xJQfOaUB6BOuqCDJkXdOoSYLdbtA+gFf6aSM1jifoQ8+Zg9gITDSTIy8bDO1HjuIMPKFsN65qoPs9/69Ew==",
                "type": 0, "callBackUrl": "https://emos.iccec.cn/?contentsType=1&level=4&contentsCode=8635"}
        headers = {'Content-Type': 'application/json',
                   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',
                   'Referer': 'https://emi.iccec.cn/31416219',
                   'Connection': 'keep-Connection'
                   }
        response = self.person.post(self.login_url, json=data, headers=headers)
        cookies = response.cookies.get_dict()
        logger.info('--> cookies: %s' % cookies)
        return cookies

    # cookie获取
    def get_cookies(self):
        cookie_dao = CookieDao()
        cookies = cookie_dao.get_cookie()
        if not cookies:
            cookies = self.__get_cookies(0)
            cookie_dao.save_cookie(cookies, expire_time=1800)
        else:
            logger.info('--> cookies: %s' % cookies)
        return cookies

    # 最大重试登录获取cookie
    def __get_cookies(self, retry):
        # 登录获取
        cookies = self.login()
        if not cookies:
            # 失败重试
            if retry <= self.max_login_retry:
                retry = retry + 1
                logger.info('--> 登录失败重试: %s次' % retry)
                return self.__get_cookies(retry)
            else:
                logger.info('--> 放弃失败重试: %s次' % retry)
                return dict()

        # 校验
        if not cookies or not self._validate_cookie(cookies):
            # 失败重试
            if retry <= self.max_login_retry:
                retry = retry + 1
                logger.info('--> 登录失败重试: %s次' % retry)
                return self.__get_cookies(retry)
            else:
                logger.info('--> 放弃失败重试: %s次' % retry)
                return dict()

        logger.info('--> 登录成功: %s次' % retry)
        return cookies

    # cookie校验
    def _validate_cookie(self, cookies):
        for must_key in self.cookie_white_list:
            # 必要字段校验
            if not cookies or (must_key not in cookies) or (cookies.get(must_key) is None) or (
                    cookies.get(must_key) == ''):
                logger.info('--> Cookie未通过校验: key=%s, cookie=%s' % (must_key, cookies))
                return False
        return True

# if __name__ == '__main__':
#     login = SeleniumLogin()
#     cookie = login.get_cookies()
#     print(cookie)
